package com.wyg.blog.controller.search;

import com.wyg.blog.service.blog.ElasticSearchService;
import com.wyg.blog.utils.JsonResult;
import com.wyg.blog.utils.UsefulConst;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

/**
 * @description:
 * @author: WYG
 * @time: 2020/12/3 15:04
 */
@RestController
@RequestMapping("/api/search")
public class SearchController {
    private static final Logger log = LoggerFactory.getLogger(SearchController.class);
    @Autowired
    ElasticSearchService elasticSearchService;

    @CrossOrigin
    @GetMapping("/searchBlog")
    public JsonResult<ArrayList<Map<String, Object>>> searchBlog(@RequestParam("keyword") String keyword,
                                                                 @RequestParam("from") Integer from,
                                                                 @RequestParam("size") Integer size) throws IOException {
        ArrayList<Map<String, Object>> searchResult = elasticSearchService.
                getSearchResult(UsefulConst.ELASTIC_BLOG_INDEX.getInformation(), keyword, from, size);
        // System.out.println(searchResult);
        ArrayList<Map<String, Object>> realResult = new ArrayList<>();
        for (Map<String, Object> result : searchResult) {
            if (result.get("published").equals(true)) {
                realResult.add(result);
            }
        }
        // System.out.println("真实结果:" + realResult);
        if (realResult.size() != 0) {
            return new JsonResult<>(realResult, UsefulConst.SUCCESSFUL_CODE);
        } else {
            return new JsonResult<>(null,UsefulConst.FAILURE_CODE);
        }
    }
}
